<template>
  <!-- 活动管理-社区管理页面 -->
  <div class="app-container calendar-list-container">
    <!-- 搜索工具栏 -->
    <section>
      <so-tool-bar :toolData="toolData" :query="listQuery" @search="search" />
    </section>
    <!-- 其他操作 -->
    <section class="filter-container">
      <el-row>
        <el-col :span="15">
          <el-button class="filter-item" type="primary" size="small" @click="haveTop(1)">置顶</el-button>
          <el-button class="filter-item" type="primary" size="small" @click="haveTop(0)">取消置顶</el-button>
        </el-col>
        <el-col :span="9">
          <section style="float: right">
            <el-button class="filter-item" type="danger" size="small" @click="delRows">批量删除</el-button>
            <el-button class="filter-item" type="primary" size="small" @click="openForm('add')">发帖</el-button>
          </section>
        </el-col>
      </el-row>
    </section>
    <!-- 表格 -->
    <el-table :data="tableList" v-loading="loading" element-loading-text="正在查询中。。。" stripe highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column align="center" width="30">
        <template slot-scope="scope">
          <i class="iconfont ali-zhiding" v-show="scope.row.top_status == 1"></i>
        </template>
      </el-table-column>
      <el-table-column align="center" label="主题" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="点击查看详情" placement="top">
            <el-button size="mini" type="text" @click="lookArticle(scope.row)">{{scope.row.article_title}}</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" label="作者" prop="create_username">
      </el-table-column>
      <el-table-column align="center" label="发布时间" prop="create_time">
      </el-table-column>
      <el-table-column align="center" label="评论量" prop="comment_nums">
      </el-table-column>
      <el-table-column align="center" label="点赞量" prop="like_nums">
      </el-table-column>
      <el-table-column align="center" label="浏览量" prop="read_nums">
      </el-table-column>
      <el-table-column align="center" label="评论">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.comment" size="mini" active-color="#13ce66" inactive-color="#C0C4CC" @change="switchChange(scope.row,$event)"></el-switch>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <el-tag size="mini" :type="audit_status[scope.row.audit_status].type">{{audit_status[scope.row.audit_status].name}}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="详情链接">
        <template slot-scope="scope">
          <el-button
            v-clipboard:copy="'https://cloud.anyolife.com/CommunityDetail' + '?id=' + scope.row.id + '&name=' + 'article'"
            v-clipboard:success="onCopy"
            v-clipboard:error="onError"
            type="text"
          >复制链接</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="230px">
        <template slot-scope="scope">
          <!-- <el-button type="text" size="mini" :disabled="scope.row.audit_status != 0" @click="pass(1,scope.row)">通过</el-button>
          <el-button type="text" size="mini" :disabled="scope.row.audit_status != 0" @click="pass(2,scope.row)">不通过</el-button> -->
          <el-button type="text" size="mini" @click="delRow(scope.row)">删除</el-button>
          <el-button type="text" size="mini" @click="editRow('edit',scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <section>
      <so-pagination :query="listQuery" @initList="initList" />
    </section>
    <!-- 发帖 -->
    <section>
      <el-dialog :visible.sync="dialog.isShow" :show-close="false" :fullscreen="fullscreen" :before-close="beforeClose" :close-on-click-modal="false">
        <el-row slot="title">
          <el-col :span="10" style="padding-top: 5px">
            <span style="font-size: 18px;">{{dialog.title}}</span>
          </el-col>
          <el-col :span="2" :offset="11">
            <el-button type="text" v-if="!fullscreen" icon="iconfont ali-quanping" @click="fullscreen = true" style="float: right"></el-button>
            <el-button type="text" v-else icon="iconfont ali-zuixiaohua" @click="fullscreen = false" style="float: right"></el-button>
          </el-col>
          <el-col :span="1">
            <el-button type="text" icon="iconfont ali-guanbi" @click="dialog.isShow = false" style="float: right"></el-button>
          </el-col>
        </el-row>
        <el-form :model="form" ref="createArticle" label-width="90px">
          <el-form-item label="主题" prop="article_title" :rules="filter_rules({required:true})">
            <el-input clearable style="width: 300px;" placeholder="请输入主题" v-model.trim="form.article_title">
            </el-input>
          </el-form-item>
          <el-form-item label="话题" prop="articletype_id" :rules="filter_rules({required:true})">
            <el-select v-model="form.articletype_id" placeholder="请选择">
              <el-option v-for="item in articleTypeList" :key="item.id" :label="item.articletype_name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="活动封面" prop="file_path" :rules="filter_rules({type: 'upload'})">
            <!-- <el-upload class="avatar-uploader" action="/api/backstage/fileUpload" name="file_path" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="form.file_path" :src="form.file_path" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload> -->
            <img v-if="form.file_path" :src="form.file_path" class="avatar" @click="sizeSet">
            <i v-else class="el-icon-plus avatar-uploader-icon" @click="sizeSet"></i>
          </el-form-item>

          <el-form-item label="论坛内容">
            <UE @showUpload="showUpload" :defaultMsg.sync='defaultMsg' ref="ue"></UE>
          </el-form-item>

          <el-form-item label="附件" prop="file_url">
              <el-upload class="upload-demo" action="/api/backstage/fileUpload" multiple :limit="5" name="file_path"
                :file-list="fileList" 
                :on-remove="handleRemove" 
                :before-remove="beforeRemove"
                :on-success='handleSuccess'
                :on-exceed="handleExceed"
                accept=".xls,.xlsx,.doc,.docx,.csv,.txt,.pdf,.ppt,.pptx"
                >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">*只能上传文件,最多上传5个</div>
              </el-upload>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialog.isShow = false">取 消</el-button>
          <el-button type="primary" @click="validate('createArticle')">提 交</el-button>
        </span>
      </el-dialog>
    </section>
    <section>
      <size-temp ref="size" :img.sync="form.file_path" title="图片设置"></size-temp>
    </section>
    <section>
      <UeUpload ref="vupload" @addUeditorImg="addUeditorImg" img="卐" title="添加图片"></UeUpload>
    </section>
  </div>
</template>
<script>
import { searchTool } from '@/utils'
import { article_list, article_edit, article_updateTopStatus, article_save, article_deleteAll, article_delete, article_findById } from '@/api/article'
// import SoWangEditor from '@/components/SoWangEditor'
import UE from '@/components/Ueditor';
import SoPagination from '@/components/SoPagination'
import SoToolBar from '@/components/SoToolBar'
import { status_opt, audit_status, toolData } from './community'
import sizeTemp from '@/components/draggableSize'
import UeUpload from '@/components/UeUpload'
import { articletype_listAll } from '@/api/articleType'

export default {
  name: "communityManage",
  components: { UE, SoPagination, SoToolBar, sizeTemp, UeUpload },
  data() {
    return {
      toolData: toolData, //搜索工具栏初始化
      loading: false,
      tableList: [],
      fileList: [],
      multipleSelection: [],
      listQuery: { start: 0, limit: 10, total: 0, current: 1 },
      audit_status: audit_status,
      status_opt: status_opt,
      dialog: { isShow: false, },
      fullscreen: false,
      fromStatus: '',
      ossPublicUrl: localStorage.getItem("ossPublicUrl"),
      form: { file_path: '' },
      articleTypeList: [],
      defaultMsg: ''
    }
  },
  methods: {
    handleRemove(file, fileList) {
      this.form.file_url = JSON.stringify(fileList);
      this.$message.success("文件删除成功！");
    },
    beforeRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleSuccess(res,file,fileList){
      if(res.status == 100){
          this.form.file_url = JSON.stringify(fileList);
          this.$message.success('上传文件成功!')
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    onCopy: function() {
      this.$message({
        type: "success",
        message: "复制成功"
      });
    },
    onError: function() {
      this.$message.error("复制失败");
    },
    showUpload(){
      console.log(1111);
      this.$refs.vupload.open()
    },
    addUeditorImg(val){
      console.log('aaa');
      this.$refs.ue.addToContent(`<img src="${val}">`)
    },
    beforeClose(done){
      this.$refs.ue.clear();
      done()
    },
    sizeSet() {
      this.$refs.size.open()
    },
    async editRow(e, row) {//编辑
      this.fromStatus = 'edit'
      let { data } = await article_findById({ id: row.id });
      if (data.status === 100) {
        this.form = data.data
        if (data.data.file_url) {
          this.fileList  = JSON.parse(data.data.file_url)
        }
        this.dialog = { isShow: true, title: '编辑' }
        this.defaultMsg = this.form.article_content
        this.$nextTick((_ => {
          this.$refs.ue.setContent(this.defaultMsg)
        }))
      }
    },
    async delRow(data) {  //删除
      let Id = data.id
      try {
        let res = await this.$confirm("确认删除吗？");
        if (res == "confirm") {
          this.loading = true;
          let { data } = await article_delete({ id: Id });
          if (data.status == 100) {
            this.$message.success("删除成功");
          }
          this.initList();
          this.loading = false;
        }
      } catch (error) {
        console.log(error, "error");
      }
    },
    lookArticle(e) {
      this.$router.push({ path: '/activity/detail', query: { id: e.id } })
    },
    async pass(num, e) {//待审核为0,通过为1,不通过为2
      e.audit_status = num;
      this.loading = true;
      await article_edit(e)
      this.loading = false;
      this.initList();
    },
    openForm() {//打开发帖dialog
      this.defaultMsg = ''
      this.fromStatus = 'add'
      this.form = { file_path: '' }
      this.fileList = [] //清空上传文件列表
      this.dialog = { isShow: true, title: '发帖' }
      this.$nextTick(_ => {
        this.$refs.ue.setContent('<br/>'); //清空富文本
      });
    },
    validate(e) {
      this.form.article_content = this.$refs.ue.getContent();//富文本内容
      this.$refs[e].validate((valid) => {
        if (valid) {
          this.saveObj();
          this.dialog.isShow = false
           this.$refs.ue.clear();
        } else {
          return false;
        }
      });
    },
    beforeAvatarUpload(file) {
      let name = file.name.split(".");
      if (
        name[name.length - 1] === "jpg" ||
        name[name.length - 1] === "jpeg" ||
        name[name.length - 1] === "png"
      ) {
        return file;
      } else {
        this.$message.error("图片只能是 jpeg/png 格式!");
        return false;
      }
    },
    handleAvatarSuccess(res, file) {
      this.form.file_path = this.ossPublicUrl + "/" + res.data.file_path;
    },
    async saveObj() {
      const params = { ...this.form, company_id: localStorage.getItem("companyId") - 0 };
      this.loading = true;
      let { data } = this.fromStatus == 'add' ? await article_save(params) : await article_edit(params);
      this.loading = false;
      if (data.status == 100) {
        this.$message.success(this.fromStatus == 'add' ? '提交成功' : '编辑成功')
        this.initList();
      }
    },
    async delRows() {//批量删除
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请先选择需要调整单元");
        return;
      }
      const ids = this.multipleSelection.map(item => item.id).join();
      try {
        const res = await this.$confirm("确认删除吗？");
        if (res == "confirm") {
          this.loading = true;
          const { data } = await article_deleteAll({ array: ids });
          if (data.status == 100) {
            this.$message.success("删除成功");
          }
          this.initList();
        }
      } catch (error) {
        console.log(error, "error");
      }
    },
    async haveTop(e) {//1 置顶 0 取消
      if (this.multipleSelection.length == 0) {
        this.$message.warning('请先选择需要调整单元');
        return;
      }
      const ids = this.multipleSelection.map(item => item.id).join();
      this.loading = true;
      let { data } = await article_updateTopStatus({ ids: ids, top_status: e });
      this.loading = false;
      if (data.status === 100) {
        await this.initList();
        this.$message.success('操作成功');
      }
    },
    async switchChange(row, e) {//是否可评论
      const params = { ...row, comment_status: ~~e }//取消内存引用问题
      this.loading = true;
      await article_edit(params)
      this.loading = false;
      this.initList();
    },
    search() {//搜索
      let keyWords = { key: 'searchDate', names: ['create_starttime', 'create_endtime'] }
      this.listQuery = searchTool(this.listQuery, keyWords);
      this.initList();
    },
    async initList() {
      this.loading = true
      const query = { ...this.listQuery, company_id: localStorage.getItem('companyId') - 0 };
      let { data } = await article_list(query);
      this.loading = false
      if (data.status == 100) {
        this.tableList = data.data.rows.map(item => {
          return { ...item, comment: !!item.comment_status }
        })
        this.listQuery.total = data.data.results;
      }
    },
    handleSelectionChange(e) {//
      this.multipleSelection = e;
    },
    async initArticleType() {
      const { data } = await articletype_listAll({ company_id: localStorage.getItem("companyId") });
      if (data.status == 100) {
        this.articleTypeList = data.data.rows;
      }
    }
  },
  created() {
    this.initList();
    this.initArticleType();
  }
}
</script>
<style lang="scss" scoped>
$border: 1px dashed #d9d9d9;
$picture-size: 120px;
$color: #606266;
span {
  font-size: 13px;
  color: $color;
}

.ali-zhiding {
  color: #009900;
  font-size: 20px;
}

.avatar-uploader {
  .el-upload {
    border: $border;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
}

.avatar-uploader-icon {
  border: $border;
  font-size: 28px;
  color: #8c939d;
  width: $picture-size;
  height: $picture-size;
  line-height: $picture-size;
  text-align: center;
  border-radius: 5px;
  cursor: pointer;
}

.avatar {
  width: 60%;
  display: block;
  border-radius: 5px;
  cursor: pointer;
}
.el-upload__tip {
  color: #F56C6C;
}
</style>
